package org.boulderfoodrescue.webapp.client.pickups.selectors;

import org.boulderfoodrescue.webapp.shared.HasEventSummary;

import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

public class TimeSlotSelectorTable extends FlowPanel implements SelectorInterface<HasEventSummary>{
	protected CellTable<HasEventSummary> table;
	protected ListDataProvider<HasEventSummary> dataProvider;
	private HasEventSummary value;
	public TimeSlotSelectorTable(){
		dataProvider = new ListDataProvider<HasEventSummary>();
		table = new CellTable<HasEventSummary>();

		/* Create all the columns */

		TextColumn<HasEventSummary> nameColumn = new TextColumn<HasEventSummary>(){
			@Override
			public String getValue(HasEventSummary object) {
				return object.getEventSummary();
			}
		};

		/* Add the columns to the table */
		table.addColumn(nameColumn, "Summary");

		dataProvider.addDataDisplay(table);

		ListHandler<HasEventSummary> sortHandler = new ListHandler<HasEventSummary>(dataProvider.getList());
		table.addColumnSortHandler(sortHandler);

		final SingleSelectionModel<HasEventSummary> selectionModel = new SingleSelectionModel<HasEventSummary>();
		table.setSelectionModel(selectionModel);
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				value = selectionModel.getSelectedObject();
			}
		});

		this.add(table);
		table.setWidth("100%");
		//this.setHeight("100%");
		table.setEmptyTableWidget(new HTML("No time slots are available to view."));
	}
	@Override
	public HasEventSummary getValue() {
		return value;
	}
	@Override
	public FlowPanel getTable() {
		return this;
	}
	@Override
	public void setValue(HasEventSummary value) {
		this.value = value;
	}
	@Override
	public String getValueAsString() {
		if(value == null)
			return "Null value";
		return value.getEventSummary();
	}
	@Override
	public void addEntry(HasEventSummary entry) {
		dataProvider.getList().add(entry);
	}
	@Override
	public void removeEntry(HasEventSummary entry) {
		dataProvider.getList().remove(entry);
	}
	@Override
	public void refreshEntries() {
		table.redraw();
	}
	
	@Override
	public void clear(){
		dataProvider.getList().clear();
	}
}
